import {
    _decorator,
    Component,
    Material,
    Vec2,
    Camera,
    Vec4,
    view,
    size,
    UITransform,
    v2,
} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ScrollForeground')
export class ScrollForeground extends Component {
    @property(Camera)
    camera: Camera | null = null;

    @property(Material)
    material: Material | null = null;

    @property(Vec4)
    speed: Vec4 = new Vec4(0.1, 0.0); // 控制滚动速度

    @property(Vec2)
    spriteSize: Vec2 = v2(128, 128);

    private _offset = new Vec4(0, 0, 0, 0);
    private _lastCameraPos = new Vec4();
    private _worldSize = size();

    start() {
        if (!this.camera || !this.material) return;
        const pos = this.camera.node.worldPosition;
        this._lastCameraPos.set(pos.x, pos.y);

        this._worldSize.set(this.spriteSize.x, this.spriteSize.y);
        // const ui = this.getComponent(UITransform);
        // if (ui) {
        //     const scale = this.node.worldScale;
        //     const rsize = view.getDesignResolutionSize();
        //     this._worldSize.set(1280 / 10, 1280 / 10);
        //     // this._worldSize.set();
        //     console.log(this._worldSize);
        // }
    }

    update(dt: number) {
        this.moveUpdate_2(dt);
    }

    moveUpdate_2(dt: number) {
        if (!this.material || !this.camera) return;

        // 计算摄像机移动量
        const movePos = this.camera.node.worldPosition;
        const dx = movePos.x - this._lastCameraPos.x;
        const dy = movePos.y - this._lastCameraPos.y;

        if (this._worldSize.x !== 0) {
            this._offset.x = dx / this._worldSize.x;
        }
        if (this._worldSize.y !== 0) {
            this._offset.y = 1 - dy / this._worldSize.y;
        }

        this._offset.x = ((this._offset.x % 1) + 1) % 1;
        this._offset.y = ((this._offset.y % 1) + 1) % 1;

        this.material.setProperty('offset', this._offset);

        if (dx + dy > 0.1) {
            console.log(dx, dy);
        }
    }

    moveUpdate_1(dt: number) {
        if (!this.material || !this.camera) return;

        // 计算摄像机移动量
        const movePos = this.camera.node.worldPosition;
        const dx = movePos.x - this._lastCameraPos.x;
        const dy = movePos.y - this._lastCameraPos.y;
        this._lastCameraPos.set(movePos.x, movePos.y);

        // 根据摄像机移动方向更新UV偏移
        // this._offset.x += dx * this.speed.x * dt;
        // this._offset.y += dy * this.speed.y * dt;
        if (this._worldSize.x !== 0) {
            this._offset.x += dx / this._worldSize.x;
        }
        if (this._worldSize.y !== 0) {
            this._offset.y += dy / this._worldSize.y;
        }

        // 保持循环 0~1
        this._offset.x = ((this._offset.x % 1) + 1) % 1;
        this._offset.y = ((this._offset.y % 1) + 1) % 1;

        this.material.setProperty('offset', this._offset);

        if (dx + dy > 0.1) {
            console.log(dx, dy);
        }
    }
}
